package com.dev.module_zqc_sleep.mvi.vm

import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.icu.util.Calendar
import androidx.lifecycle.ViewModel
import com.dev.module_zqc_sleep.broadcast.AlarmReceiver
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class AlarmViewModel : ViewModel() {

    private val _selectedTime = MutableStateFlow("")
    val selectedTime = _selectedTime.asStateFlow()

    private val _audioPath = MutableStateFlow(Pair("", ""))
    val audioPath = _audioPath.asStateFlow()

    private val _isAlarmEnabled  = MutableStateFlow(false)
    val isAlarmEnabled = _isAlarmEnabled.asStateFlow()

    fun updateSelectedTime(context: Context, selectedTime: String) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        with(sharedPref.edit()) {
            putString("get_up_time", selectedTime)
            apply()
        }
        _selectedTime.value = selectedTime
    }

    fun updateAudioPath(audioName: String, audioPath: String) {
        _audioPath.value = Pair(audioName, audioPath)
    }

    fun parseTimeAndSetAlarm(context: Context, selectedTime: String) {
        val timeParts = selectedTime.split(":")
        val hours = timeParts[0].toInt()
        val minutes = timeParts[1].toInt()

        val now = Calendar.getInstance()
        val alarmTime = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, hours)
            set(Calendar.MINUTE, minutes)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)

            if (before(now)) {
                add(Calendar.DATE, 1)
            }
        }

        setAlarm(context, alarmTime.timeInMillis)
    }

    private fun setAlarm(context: Context, alarmTimeInMillis: Long) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTimeInMillis, pendingIntent)
    }

    fun cancelAlarm(context: Context) {
        AlarmReceiver.mediaPlayer?.stop()
        AlarmReceiver.mediaPlayer?.release()
        AlarmReceiver.mediaPlayer = null

        // 取消闹钟
        val alarmId = getAlarmId(context)
        if (alarmId != 0) {
            AlarmReceiver.mediaPlayer?.stop()
            AlarmReceiver.mediaPlayer?.release()
            AlarmReceiver.mediaPlayer = null

            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val cancelIntent = Intent(context, AlarmReceiver::class.java)
            val cancelPendingIntent = PendingIntent.getBroadcast(context, alarmId, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
            alarmManager.cancel(cancelPendingIntent)

            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.cancel(alarmId)
        }

        removeSelectedTime(context)
    }

    fun saveAlarmSetting(
        context: Context,
        audioPath: String,
        useVibrator: Boolean,
        alarmVolume: Float
    ) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        with(sharedPref.edit()) {
            putString("audioPath", audioPath)
            putBoolean("vibrator", useVibrator)
            putFloat("alarm_volume", alarmVolume)
            apply()
        }
    }

    private fun getAlarmId(context: Context): Int {
        val sharedPreferences = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        val currentId = sharedPreferences.getInt("alarmId", 0)
        return currentId
    }

    fun readAlarmEnabled(context: Context) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        val state = sharedPref.getBoolean("isAlarmEnabled", false)
        _isAlarmEnabled.value = state
    }

    fun toggleAlarmEnabled(context: Context) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        val newState = !sharedPref.getBoolean("isAlarmEnabled", false)
        with(sharedPref.edit()) {
            putBoolean("isAlarmEnabled", newState)
            apply()
        }
        _isAlarmEnabled.value = newState
    }

    fun loadSelectedTime(context: Context) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        _selectedTime.value = sharedPref.getString("get_up_time", "") ?: ""
    }

    private fun removeSelectedTime(context: Context) {
        val sharedPref = context.getSharedPreferences("AlarmPreferences", Context.MODE_PRIVATE)
        with(sharedPref.edit()) {
            remove("get_up_time")
            apply()
        }
        _selectedTime.value = ""
    }

}